package tsinghua.smxq.mc;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import tsinghua.smxq.foodprice.FoodandFoodId;
import tsinghua.smxq.foodprice.HttpConnection;
import tsinghua.smxq.foodprice.TimeFormatTransform;
import tsinghua.smxq.mc.FoodPriceRequestActivity.SelectProvince;
import tsinghua.smxq.utilitiespayment.Record;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class FoodPriceSubmitActivity extends Activity {
	private List<String> proset = new ArrayList<String>();
	ArrayList<String> city_list = new ArrayList<String>();
	ArrayList<String> foodcategory_list = new ArrayList<String>();
	ArrayList<String> foodname_list = new ArrayList<String>();
	ArrayAdapter<String> pro_adapter, city_adapter, foodcategory_adapter,
			foodname_adapter;
	Spinner pro_spinner, city_spinner, foodcategory_spinner, foodname_spinner;
	String city, foodcategory, foodname;
	private int cityID = -1;
	private int pro_id;
	private int foodID = -1;
	private float foodprice;
	private String date; // 时间
	TimeZone timeZ;// 时区
	SimpleDateFormat sdf; // 格式
	ImageButton start_button;
	RadioGroup radiogroup;
	RadioButton radiobutton1, radiobutton2;
	Toast toast;
	String[] cityls, foodnamels, foodcategoryls;
	EditText price_editText;
	URL url;
	String operationResult = "failure";
	private File f = new File("/data/data/tsinghua.smxq.mc/databases/data.db");

	ImageButton mBtnChooseType = null;
	Button backToMain;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.foodpricesubmit);

		pro_spinner = (Spinner) findViewById(R.id.pros_submit_Spinner);
		pro_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, getProSet());
		pro_spinner.setAdapter(pro_adapter);
		pro_spinner.setOnItemSelectedListener(new SelectProvince());

		city_spinner = (Spinner) findViewById(R.id.cities_submit_Spinner);
		city_spinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						city = city_spinner.getSelectedItem().toString();
						cityID = arg2 + 1;
						arg0.setVisibility(View.VISIBLE);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}
				});

		// 食物类别
		foodcategory_spinner = (Spinner) findViewById(R.id.foodcategory_submit_Spinner);
		foodcategoryls = getResources().getStringArray(R.array.foodcategories);
		// 获取XML中定义的数组
		foodcategory_list.clear();
		for (int i = 0; i < foodcategoryls.length; i++) {
			foodcategory_list.add(foodcategoryls[i]);
		}
		// 把数组导入到spinner中
		foodcategory_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, foodcategory_list);
		// 设置下拉菜单的风格
		foodcategory_adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 绑定适配器
		foodcategory_spinner.setAdapter(foodcategory_adapter);
		foodcategory_spinner.setPrompt("食物类别");
		foodcategory_spinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						UpdateFoodName_Spinner(arg2);
						arg0.setVisibility(View.VISIBLE);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});

		// 食物名称
		foodname_spinner = (Spinner) findViewById(R.id.foodname_submit_Spinner);
		foodname_spinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						foodname = foodname_spinner.getSelectedItem()
								.toString();
						foodID = arg2 + 2;
						arg0.setVisibility(View.VISIBLE);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}
				});

		// 获得价格
		price_editText = (EditText) findViewById(R.id.foodprice_edittext);
		// 获得开始按钮
		start_button = (ImageButton) findViewById(R.id.imgbutton_submit_start);
		start_button.setOnClickListener(new OnClickListener() {// 添加按钮监听器
					public void onClick(View v) {
						// 连接服务器
						if (foodname_spinner.getSelectedItem().toString()
								.compareTo("") == 0) {
							DisplayToast("请选择菜的名称", 1);
						} else {
							foodprice = Float.parseFloat(price_editText
									.getText().toString().trim());
							date = TimeFormatTransform.getCurrentDate();
							// 连接服务器，传递各种信息
							try {
								url = new URL("http://" + Constants.serverIP
										+ ":8080/MobileCityServer/addQuote.do?"
										+ "userId=" + Session.user.getId()
										+ "&cityId=" + cityID + "&foodId="
										+ foodID + "&price=" + foodprice
										+ "&priceDate=" + date);
								operationResult = HttpConnection
										.httpConnection(url);
								// 此处对operationResult进行解析，更新
								if (operationResult
										.compareToIgnoreCase("success") == 0) {
									DisplayToast("菜价上传成功!", Toast.LENGTH_SHORT);
								} else if (operationResult
										.compareToIgnoreCase("failure") == 0) {
									DisplayToast("菜价上传失败，请查看网络是否正常",
											Toast.LENGTH_SHORT);
								} else {
									DisplayToast("当前还没有连接网络",
											Toast.LENGTH_SHORT);
								}
								Intent gotoIntent = new Intent(
										FoodPriceSubmitActivity.this,
										HistoryChartActivity.class);
								FoodPriceSubmitActivity.this
										.startActivity(gotoIntent);
							} catch (MalformedURLException e) {
								e.printStackTrace();

							} catch (IOException e) {
								e.printStackTrace();
							}
						}

					}
				});
		mBtnChooseType = (ImageButton) findViewById(R.id.ib_chooseType);
		mBtnChooseType.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(FoodPriceSubmitActivity.this)
						.setTitle("菜价搜索功能")
						.setItems(new String[] { "菜价搜索", "菜价提交", "历史菜价" },
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										if (which == 0) {
											Intent intent = new Intent();
											intent.setClass(
													FoodPriceSubmitActivity.this,
													FoodPriceRequestActivity.class);
											FoodPriceSubmitActivity.this
													.startActivity(intent);
										} else if (which == 1) {
											return;
										} else if (which == 2) {
											Intent intent = new Intent();
											intent.setClass(
													FoodPriceSubmitActivity.this,
													HistoryChartActivity.class);
											FoodPriceSubmitActivity.this
													.startActivity(intent);

										}

									}
								}).create().show();
			}

		});

		backToMain = (Button) findViewById(R.id.foodprice_back);
		backToMain.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				FoodPriceSubmitActivity.this.startActivity(new Intent(
						FoodPriceSubmitActivity.this,
						FoodPriceRequestActivity.class));
				FoodPriceSubmitActivity.this.overridePendingTransition(
						R.anim.push_in, R.anim.push_out);
				FoodPriceSubmitActivity.this.finish();
			}

		});

	}

	/**
	 * 返回 省份集合
	 */
	public List<String> getProSet() {
		SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
		Cursor cursor = db1.query("provinces", null, null, null, null, null,
				null);
		while (cursor.moveToNext()) {
			String pro = cursor.getString(cursor.getColumnIndexOrThrow("name"));
			proset.add(pro);
		}
		cursor.close();
		db1.close();
		return proset;
	}

	class SelectProvince implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			// TODO Auto-generated method stub
			pro_id = position;
			city_spinner.setAdapter(getAdapter());

		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}
	}

	public ArrayAdapter<String> getAdapter() {
		ArrayAdapter<String> adapter1 = new ArrayAdapter(this,
				android.R.layout.simple_spinner_item, getCitSet(pro_id));
		return adapter1;
	}

	/**
	 * 返回 城市集合
	 */
	public List<String> getCitSet(int pro_id) {
		city_list.clear();
		SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
		Cursor cursor = db1.query("citys", null, "province_id=" + pro_id, null,
				null, null, null);
		while (cursor.moveToNext()) {
			String pro = cursor.getString(cursor.getColumnIndexOrThrow("name"));
			city_list.add(pro);
		}
		cursor.close();
		db1.close();
		return city_list;
	}

	public void DisplayToast(String str, int time) {
		toast = Toast.makeText(this, str, time);
		// 设置toast显示的位置
		toast.setGravity(Gravity.TOP, 0, 320);
		// 显示该Toast
		toast.show();
	}

	public void UpdateFoodName_Spinner(int selectedcategory) {
		foodname_list.clear();
		switch (selectedcategory) {
		case 0:
			foodnamels = getResources().getStringArray(R.array.Meat);
			// 获取XML中定义的数组
			for (int i = 0; i < foodnamels.length; i++) {
				foodname_list.add(foodnamels[i]);
			}
			break;
		case 1:
			foodnamels = getResources().getStringArray(R.array.Vegetable);
			// 获取XML中定义的数组
			for (int i = 0; i < foodnamels.length; i++) {
				foodname_list.add(foodnamels[i]);
			}
			break;
		case 2:
			foodnamels = getResources().getStringArray(R.array.CookedFood);
			// 获取XML中定义的数组
			for (int i = 0; i < foodnamels.length; i++) {
				foodname_list.add(foodnamels[i]);
			}
			break;
		}
		// 把数组导入到spinner中
		foodname_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, foodname_list);
		// 设置下拉菜单的风格
		foodname_adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 绑定适配器
		foodname_spinner.setAdapter(foodname_adapter);
		foodname_spinner.setPrompt("食物名称");
	}

	protected void showInfoDialog(String tolook) {
		AlertDialog.Builder adb = new AlertDialog.Builder(this)
		/** 设置标题 **/
		.setTitle("URL")
		/** 设置icon **/
		.setIcon(android.R.drawable.alert_dark_frame)
		/** 设置内容 **/
		.setMessage(tolook);
		adb.setNegativeButton("关闭", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		adb.show();
	}

	/*
	 * 增加新的市场和菜价 protected void showAddDialog() { LayoutInflater factory =
	 * LayoutInflater.from(this); final View textEntryView =
	 * factory.inflate(R.layout.newmarketfood_dialog, null); final TextView
	 * city_TextView = (TextView)
	 * textEntryView.findViewById(R.id.city_dialog_textview1); final TextView
	 * foodName_TextView =
	 * (TextView)textEntryView.findViewById(R.id.foodname_dialog_textview1);
	 * final EditText foodPrice_editText =
	 * (EditText)textEntryView.findViewById(R.id.foodprice_dialog_edittext);
	 * AlertDialog.Builder ad1 = new
	 * AlertDialog.Builder(FoodPriceSubmitActivity.this); ad1.setTitle("增加新菜价");
	 * ad1.setView(textEntryView); ad1.setPositiveButton("提交", new
	 * DialogInterface.OnClickListener() { public void onClick(DialogInterface
	 * dialog, int i) { foodprice =
	 * Float.parseFloat(foodPrice_editText.getText().toString().trim()); try {
	 * Field field =
	 * dialog.getClass().getSuperclass().getDeclaredField("mShowing");
	 * field.setAccessible(true); field.set(dialog, true); } catch (Exception e)
	 * { e.printStackTrace(); } //此处显示可以改成等待的那个对话框
	 * DisplayToast("城市："+city+"\n"+"菜名："
	 * +foodname+"\n"+"价格："+foodprice+"\n正在提交给服务器，请确定连接了网络",2);
	 * //连接服务器，将信息传给服务器端 date = TimeFormatTransform.getCurrentDate(); try { url
	 * = new
	 * URL("http://"+Constants.serverIP+":8080/MobileCityServer/addQuote.do?"
	 * +"userId="+Session.user.getId() +"&cityId="+cityID +"	&foodId="+foodID
	 * +"&price="+foodprice +"&priceDate="+date); //operationResult =
	 * HttpConnection.httpConnection(url); //此处对OperationResult进行解析
	 * if(operationResult.compareToIgnoreCase("success")==0) {
	 * DisplayToast("菜价上传成功!",Toast.LENGTH_SHORT); } else
	 * if(operationResult.compareToIgnoreCase("failure")==0) {
	 * DisplayToast("菜价上传失败，请查看网络是否正常",Toast.LENGTH_SHORT); } else {
	 * DisplayToast("当前还没有尝试连接网络",Toast.LENGTH_SHORT); }
	 * 
	 * city_spinner.setSelection(0); foodcategory_spinner.setSelection(0);
	 * Intent gotoIntent = new Intent(FoodPriceSubmitActivity.this,
	 * FoodPriceActivity.class);
	 * FoodPriceSubmitActivity.this.startActivity(gotoIntent);
	 * 
	 * } catch (MalformedURLException e) { e.printStackTrace();
	 * 
	 * } catch (IOException e) { e.printStackTrace(); } } });
	 * ad1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
	 * public void onClick(DialogInterface dialog, int i) { try { Field field =
	 * dialog.getClass().getSuperclass().getDeclaredField("mShowing");
	 * field.setAccessible(true); field.set(dialog,true); } catch (Exception e)
	 * { e.printStackTrace(); } } }); ad1.show();
	 * 
	 * }
	 */
}
